/**
 * 视频播放
 */
define(function(require,exports,module) {
    var oPlayerCenter = $(".js_playerCenter");

    oPlayerCenter.each(function (i) {
        ddjVideo(oPlayerCenter.eq(i));
    });

    function ddjVideo(obj, auto) {
        var oWindow = $(window);
        var oWrap = $('.js_wrap');
        var playerVideo = obj.find('.js_player-video');
        var playerLayer = obj.find('.js_player-layer');
        var video = obj.find('.js_myVideo')[0];
        var playerControlBtn = obj.find('.js_player-control-btn');
        var playerControlBar = obj.find('.js_player-control-bar');
        var playerBtn = obj.find('.js_player-btn');
        var playerProcessBox = obj.find('.js_player-process-box');
        var playerProcessBar = obj.find('.js_player-process-bar');
        var playerProcessRang = obj.find('.js_player-process-rang');
        var playerProcessBtn = obj.find('.js_player-process-btn');
        var playerRepeat = obj.find('.js_player-repeat');
        var playerWaiting = obj.find('.js_player-waiting');
        var $now = obj.find('.js_now');
        var $total = obj.find('.js_total');
        var oUserSelet = obj.parents('.js_playVideo').siblings('.js_userSelet');
        var playerControlAll = obj.find('.js_player-control-all');
        var resizeTimer = false;
        var progressFlag;
        var startTime = '';
        var bufferingstart = '';

        var nTime = 5;
        var oAutoPlayBox = obj.find('.js_autoPlayBox');        // 倒计时经度
        var oNextTimeProcess = obj.find('.js_nextTimeProcess');        // 倒计时经度


        var videoPlayer = {
            init: function(){
                $(video).removeAttr("controls");
                bindEvent(video, "loadeddata", videoPlayer.initControls);
                bindEvent(video, "loadstart", videoLoadstart);
                bindEvent(video, "ended", videoEnded);
                bindEvent(video, "waiting", videoWaiting);
                bindEvent(video, "canplay", videoCanplay);
                bindEvent(video, "play", playerStart);
                bindEvent(video, "pause", playerEnd);
                bindEvent(video, "error", videoError);
                bindEvent(video, "seeking",videoSeeking);
                bindEvent(video, "seeked",videoSeeked);
                videoPlayer.operateControls();
            },
            initControls: function(){
                console.log('视频加载结束');
                var opentime = new Date().getTime();
                var preparedTime =opentime-startTime;
                $total.html(videoPlayer.formatPlayTime(video.duration));
            },
            operateControls: function(){
                bindEvent(playerControlBtn, "click", play);
                bindEvent(playerVideo, "click", showControls);
                bindEvent(playerBtn, "click", play);
                bindEvent(playerRepeat.find('button'), "click", function () {
                    play();
                    checkAutoPlayNext(true);
                });
                bindEvent(playerProcessBox,"touchstart", enhanceVideoSeek);
                bindEvent(playerProcessBox,"touchmove", enhanceVideoSeek);
                bindEvent(playerProcessBox,"touchend", play);
                bindEvent(oUserSelet.find('li'),"click", function () {
                    VideChange($(this));
                    checkAutoPlayNext(true);
                });
                bindEvent(playerControlAll,"click", requestFullScreen);
                bindEvent(oAutoPlayBox,"click", autoPlayTipClose);
                unbindTouch(playerControlBar);
            },
            formatPlayTime:function(time){
                var timeStr = time.toString().split('.')[0];
                if(timeStr<=60){
                    timeStr = timeStr>=10?timeStr:"0"+timeStr;
                    return "00:00:"+timeStr;
                }else if(timeStr>60 && timeStr <=3600){
                    var minutes = Math.floor(timeStr/60);
                    minutes = (minutes>=10)?minutes:'0'+minutes;
                    var second = timeStr%60;
                    second = (second>=10)?second:'0'+second;
                    return '00:'+minutes+':'+second;
                }else{
                    var hour = Math.floor(timeStr/3600);
                    hour = (hour>=10)?hour:'0'+hour;
                    var minutes = Math.floor(timeStr%3600/60);
                    minutes = (minutes>=10)?minutes:'0'+minutes;
                    var second = timeStr%60;
                    second = (second>=10)?second:'0'+second;
                    return hour+':'+minutes+':'+second;
                }
            }
        }

        videoPlayer.init();

        function bindEvent(ele, eventName, func){
            $(ele).off(eventName);
            $(ele).on(eventName, func);
        }

        function unbindTouch(ele){
            ele.ontouchmove = function(event){
                event.preventDefault && event.preventDefault();
                event.returnValue = false;
                event.stopPropagation && event.stopPropagation();
                return false;
            }
        }

        function showControls(){
            playerControlBar.css({'visibility': 'visible' });
            clearTimeout(video.showControl_time);
            video.showControl_time = setTimeout(hideControls, 3000);
        }

        function hideControls(){
            playerControlBar.css({'visibility': 'hidden' });
        }

        function videoLoadstart(){
            // console.log('视频正在加载');
            return startTime = new Date().getTime();
        }

        function playerStart(){
            $(playerControlBtn).addClass('pause').removeClass('play');
            $(playerBtn).addClass('pause').removeClass('play');
            playerLayer.hide();
            playerRepeat.hide();
            var videoId = $(this).attr('videoId');
            var isAnime = $(this).attr('isAnime');
            G_JSON_GET('/video/calcCount?isAnime='+isAnime+'&videoId=' + videoId); //统计播放次数
        }


        function playerEnd(){
            $(playerControlBtn).addClass('play').removeClass('pause');
            $(playerBtn).addClass('play').removeClass('pause');
            playerControlBar.css({'visibility': 'visible'});
        }

        function play(){
            if ( video.paused || video.ended ){
                //播放
                video.play();
                playerBtn.hide();
                progressFlag = setInterval(getProgress, 60);
            }else{
                //暂停
                video.pause();
                playerBtn.show();
                clearTimeout(video.showControl_time);
                clearInterval(progressFlag);
            }
        }

        function getProgress(){
            var percent = video.currentTime / video.duration;
            var ProgressOffsetWidth = percent * (playerProcessBar.outerWidth());

            playerProcessRang.css({'width': ProgressOffsetWidth});
            playerProcessBtn.css({'left': ProgressOffsetWidth -10});

            $now.html(videoPlayer.formatPlayTime(video.currentTime));
        }

        function videoWaiting(){
            playerWaiting.show();
        }

        function videoCanplay(){
            playerWaiting.hide();
        }

        function videoError(){
            var videoError = video.error.code;
            var videoErrorStr = '';
            switch(videoError){
                case 1:
                    videoErrorStr='取回过程被用户中止';
                    break;
                case 2:
                    videoErrorStr='当下载时发生错误';
                    break;
                case 3:
                    videoErrorStr='当解码时发生错误';
                    break;
                case 4:
                    videoErrorStr='不支持音频/视频';
                    break;
            }
            if(videoError){
                // window.location.href=error_url+'?state=4';
            }
        }

        // 视频结束
        function videoEnded(e){
            playerEnd();
            video.currentTime = 0;
            playerProcessRang.css({'width': 0});
            playerProcessBtn.css({'left': 0});
            clearInterval(progressFlag);
            playerRepeat.show();
            playerControlBar.css({'visibility':'hidden'});
            playerBtn.hide();
            obj.removeClass('actFixed');
            checkAutoPlayNext();
            // console.log('over')
        }

        function videoSeeking(){
            playerWaiting.show();
        }

        function videoSeeked(){
            var bufferingend = new Date().getTime();
            var buffertime = bufferingend-bufferingstart;
            playerWaiting.hide();
        }

        // 拖拽
        function enhanceVideoSeek(e){
            var touch = e.originalEvent.targetTouches[0];
            var pageX = touch.pageX;
            var length = pageX - playerProcessBar.offset().left;
            var percent = length / playerProcessBar.outerWidth();
            var ProgressOffsetWidth = percent * (playerProcessBar.outerWidth());
            if(ProgressOffsetWidth<=0) {
                ProgressOffsetWidth = 0;
            }
            else if (ProgressOffsetWidth >= playerProcessBar.outerWidth() - 5) {
                ProgressOffsetWidth = playerProcessBar.outerWidth() - 5;
            }

            playerProcessRang.css({'width': ProgressOffsetWidth});
            playerProcessBtn.css({'left': ProgressOffsetWidth -10});
            if(isNaN(video.duration)) {
                video.currentTime =  0;
            }else {
                video.currentTime =  (percent * video.duration)*100/100;
            }

            video.pause();
            showControls();
            progressFlag = setInterval(getProgress, 60);


        }

        // 换集
        function VideChange(obj) {
            var index = obj.index();
            if(index == oUserSelet.find('li').length-1)  return;
            var sourceSrc =  obj.attr('videoHref');
            var sourceDescription = obj.attr('videoDescription');
            var sourceVideoImg = obj.attr('videoImg');
            var sourceVideoId = obj.attr('videoId');
            playerRepeat.css('background-image','url('+sourceVideoImg+')');
            oWrap.find('.js_video_miaoshu').text(sourceDescription);
            oUserSelet.find('li').removeClass('active').eq(index).addClass('active');
            if($(video).attr('_index') != index) {
                $(video).attr('_index', index);
                $(video).attr('poster', sourceVideoImg);
                $(video).attr('videoId', sourceVideoId);
                $(video).find('source').attr('src',sourceSrc);
                video.load();
                play();
            }

        }

        // 放大
        function VideLarge() {
            if($(this).hasClass('active')) {
                $(this).removeClass('active');
                oWrap.css({'z-index': 1});
                obj.removeClass('actFixed');
                $('html').removeClass('Height100');
                oPlayerCenter.off("touchmove");
            }
            else {
                $(this).addClass('active');
                oWrap.css({'z-index': 120});
                obj.addClass('actFixed');
                $('html').addClass('Height100');
                oPlayerCenter.on("touchmove",function(e) {e.preventDefault()});
            }
        }

        // 检测是否显示自动播放下一集
        function checkAutoPlayNext(off) {
            if(auto === 'auto') {
                if(off) {
                    autoPlayTipClose();
                }
                else {
                    var nextIndex = oUserSelet.find('li.active').index()+1;
                    if(nextIndex < oUserSelet.find('li').length-1) {
                        autoPlayTip(nTime, function () {
                            VideChange(oUserSelet.find('li').eq(nextIndex));
                        })
                    }
                    else {
                        autoPlayTipClose();
                    }
                }
            }
        }


        // 自动播放下一集倒计时
        function autoPlayTip(nTime, fn) {
            oAutoPlayBox.show();

            oNextTimeProcess.stop().animate({
                'width': '100%'
            }, nTime*1000, function () {
                oAutoPlayBox.hide();
                oNextTimeProcess.stop().css({'width': 0});
                if(fn)fn();

            });
        }

        // 暂停 自动播放下一集倒计时
        function autoPlayTipClose() {
            oNextTimeProcess.stop().css({'width': 0});
            oAutoPlayBox.hide();
        }


        //进入全屏
        function requestFullScreen() {
            video.webkitEnterFullscreen(); 
        }

    }

    exports.ddjVideo = ddjVideo;

})

